package mh.demo.springboot.file;

import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * MultipartFile转换为File、File转换为MultipartFile的demo
 */
@RestController
@RequestMapping
public class FileController {

    private static final String UPLOAD_DIR = "E:/downtest";

    @PostMapping("{version}/file")
    public ResponseEntity<String> upload(@PathVariable("version") String version,
                                         @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("文件是空，无需上传");
        }
        File destFile = new File(UPLOAD_DIR + File.separator + file.getOriginalFilename());
        File parentFile = destFile.getParentFile();
        if (!parentFile.exists()) {
            if (!parentFile.mkdirs()) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("内部错误");
            }
        }
        if ("v1".equals(version)) {
            return uploadByV1(file, destFile);
        } else if ("v2".equals(version)) {
            return uploadByV2(file, destFile);
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("请求错误");
        }
    }

    private ResponseEntity<String> uploadByV1(MultipartFile file, File destFile) {
        try {
            // 将MultipartFile转换到File，并按File的路径输出
            file.transferTo(destFile);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("内部错误");
        }
        return ResponseEntity.ok("附件上传成功");
    }

    private ResponseEntity<String> uploadByV2(MultipartFile file, File destFile) {
        try (FileOutputStream out = new FileOutputStream(destFile)) {
            out.write(file.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("内部错误");
        }
        return ResponseEntity.ok("附件上传成功");
    }

    @GetMapping("/file/{filename}")
    public ResponseEntity<?> download(@PathVariable("filename") String filename) {
        File destFile = new File(UPLOAD_DIR + File.separator + filename);
        if (!destFile.exists()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("没有此文件");
        }
        filename = URLEncoder.encode(filename, StandardCharsets.UTF_8);
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType("application/x-download"))
                .header("Content-Disposition", "attachment;filename=" + filename)
                .contentLength(destFile.length())
                .body(new FileSystemResource(destFile));

    }

}
